package com.king.juc.shared.exercise;

import java.util.Random;

/**
 * 转账线程安全Demo
 *      边界为 money, 两个对象各自的变量, 需要对类进行加锁
 * @author king
 * @date 2020/10/28 18:26
 */
public class ExerciseTransfer {
    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("total: " + (a.getMoney() + b.getMoney()));
    }


    /**
     * 线程安全
     */
    static Random random = new Random();
    /**
     * 生成随机数
     * @return 1 ~ 5
     */
    public static int randomAmount(){
        return random.nextInt(5) + 1;
    }
}
